/**
 * Created by 叶子 on 2017/8/13.
 */
import React, { Component } from 'react';
import { Route, Redirect, Switch } from 'react-router-dom';
import AllComponents from '../components';
import routesConfig from './config';
import moment from 'moment';
import {message} from 'antd';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

export default class CRouter extends Component {
    constructor(props){
        super(props);
    }


    requireAuth = (permission, component) => {
        const permissions = JSON.parse(localStorage.getItem('user')).permission;
        if (!permissions || (!permissions.includes(permission)&& permission.split(':')[0] !== permissions[permissions.length - 1].split(':')[0])) {
            return <Redirect to={'/404'} />;
        }
        return component;
    };
    requireLogin = (component, permission) => {
        const user = localStorage.getItem('user');
        if(!user){
            /*message.warning('会话已过期,请重新登录!',2);*/
            return <Redirect to={'/login'} />;
        }
        return permission ? this.requireAuth(permission, component) : component;
    };
    render() {
        return (
            <Switch>
                {
                    Object.keys(routesConfig).map(key => 
                        routesConfig[key].map(r => {
                            const route = r => {
                                const Component = AllComponents[r.component];
                                return (
                                    <Route
                                        key={r.route || r.key}
                                        exact
                                        path={r.route || r.key}
                                        component={props => r.login ? 
                                            <Component {...props} />
                                            : this.requireLogin(<Component {...props} />, r.permission)}
                                    />
                                )
                            }
                            return r.component ? route(r) : r.subs.map(r => r.component ? route(r) : r.subs.map(r => route(r)));
                        })
                    )
                }

                <Route render={() => <Redirect to="/login" />} />
            </Switch>
        )
    }
}